package com.markerhub.controller;

import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.CourseService;
import com.markerhub.service.ManagerStudentService;
import com.markerhub.service.UserService;
import com.markerhub.shiro.AccountProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.UsesSunMisc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/teacher")
public class TeacherStatsController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private ManagerStudentService studentService;
    @Autowired
     UserService userService;

    @GetMapping("/stats")
    @RequiresAuthentication
    public Result getTeacherStats() {
        // 修改这里：使用 AccountProfile 而不是 User
        Subject subject = SecurityUtils.getSubject();
        AccountProfile accountProfile = (AccountProfile) subject.getPrincipal();

        // 通过 AccountProfile 获取用户ID
        Long teacherId = accountProfile.getId();

        try {
            Map<String, Object> stats = new HashMap<>();

            // 获取教师基本信息
            User teacherInfo = userService.getById(teacherId);
            stats.put("teacherName", teacherInfo.getUsername());
            stats.put("email", teacherInfo.getEmail());
            stats.put("lastLogin", teacherInfo.getLastLogin());

            // 获取课程统计
            stats.put("totalCourses", courseService.countTeacherCourses(teacherId));
            stats.put("activeCourses", courseService.countTeacherActiveCourses(teacherId));
            stats.put("totalStudents", studentService.countTeacherStudents(teacherId));

            return Result.succ(stats);
        } catch (Exception e) {
            log.error("获取教师统计数据失败", e);
            return Result.fail("获取统计数据失败");
        }
    }
}
